<?php

namespace app\one_wxopen\openapi;

use app\common\controller\Common;
use app\one_wxopen\service\WeTool;
use think\facade\Log;

class Auth extends Common
{
    public function __construct()
    {
        Log::init([
            // 日志记录级别
            'level'       => ['wxopen'],
            // 独立日志级别
            'apart_level' => ['wxopen'],
        ]);
    }
    public function ticket()
    {
        trace('ticket'.PHP_EOL.var_export(file_get_contents("php://input"),true),'wxopen');
        try {
            // 实例服务接口
            $server = WeTool::service();
            // 获取并更新Ticket推送
            if (!($data = $server->getComonentTicket())) {
                return "Ticket event handling failed.";
            }
        } catch (\Exception $e) {
            return "Ticket event handling failed, {$e->getMessage()}";
        }
        trace('ticket data'.PHP_EOL.var_export($data,true),'wxopen');
        if (!empty($data['AuthorizerAppid']) && isset($data['InfoType'])) {
            $file = env('app_path').'one_wxopen'.DIRECTORY_SEPARATOR.'mpdata'.DIRECTORY_SEPARATOR.$data['AuthorizerAppid'].'.ini';
            $_file = new \one\WriteIniFile($file);
            # 授权成功通知
            if ($data['InfoType'] === 'authorized') {
                $_file->update($data)->write();
                try {
                    $detail = $server->getQueryAuthorizerInfo($data['AuthorizationCode']);
                    $_file->update(['authorizer_refresh_token'=>$detail['authorizer_refresh_token']])->write();
                } catch (\Exception $e) {
                    return "{$e->getMessage()}";
                }
                // var_dump($data,$detail);
                runhook('wxopen_after_authorized',$data);
            }
            # 接收取消授权服务事件
            if ($data['InfoType'] === 'unauthorized') {
                $oldname = $file;
                $newname = str_replace($data['AuthorizerAppid'],$data['AuthorizerAppid'].'_unauthorized',$oldname);
                if(file_exists($oldname)){
                    rename($oldname,$newname);
                }
                runhook('wxopen_after_unauthorized',$data);
            }
            # 授权更新通知
            if ($data['InfoType'] === 'updateauthorized') {
                $_file->update($data)->write();
                runhook('wxopen_after_updateauthorized',$data);
            }
        }
        return 'success';
    }
    public function message($appid)
    {
        trace('message'.PHP_EOL.var_export(file_get_contents("php://input"),true),'wxopen');
        try {
            $server = WeTool::service();
            $wechat =  $server->instance('Receive', $appid, 'WeChat');
        } catch (\Exception $e) {
            return "Wechat message handling failed, {$e->getMessage()}";
        }
        $receive = $wechat->getReceive();
        trace('message receive'.PHP_EOL.var_export($receive,true),'wxopen');
        if (in_array($appid, ['wx570bc396a51b8ff8', 'wxd101a85aa106f53e'])) {
            # 全网发布接口测试
            /* 分别执行对应类型的操作 */
            switch (strtolower($wechat->getMsgType())) {
                case 'text':
                    if ($receive['Content'] === 'TESTCOMPONENT_MSG_TYPE_TEXT') {
                        //测试公众号处理用户消息
                        //微信模推送给第三方平台方：文本消息，其中 Content 字段的内容固定为：TESTCOMPONENT_MSG_TYPE_TEXT
                        //第三方平台方立马回应文本消息并最终触达粉丝：Content 必须固定为：TESTCOMPONENT_MSG_TYPE_TEXT_callback
                        return $wechat->text('TESTCOMPONENT_MSG_TYPE_TEXT_callback')->reply([], true);
                    } else {
                        //测试公众号使用客服消息接口处理用户消息
                        $key = str_replace("QUERY_AUTH_CODE:", '', $receive['Content']);
                        $server->getQueryAuthorizerInfo($key,$receive['Content']);
                        $data =[
                            'touser'      => $receive['FromUserName'],
                            'msgtype'   => 'text',
                            'text'      => ['content'=>"{$key}_from_api"],
                        ];
                        $custom = $server->instance('Custom', $appid, 'WeChat');
                        return $custom->send($data);
                    }
                case 'event':
                    return $wechat->text("{$receive['Event']}from_callback")->reply([], true);
                default:
                    return 'success';
            }
        } else {
            # 接口类正常服务
            try {
                list($data, $openid) = [$receive, $wechat->getOpenid()];
                if (isset($data['EventKey']) && is_object($data['EventKey'])) $data['EventKey'] = (array)$data['EventKey'];
                $input = ['openid' => $openid, 'appid' => $appid, 'receive' => serialize($data), 'encrypt' => intval($wechat->isEncrypt())];
                // TODO 
                // if (is_string($result = http_post($config['appuri'], $input, ['timeout' => 30]))) {
                //     if (is_array($json = json_decode($result, true))) {
                //         return $wechat->reply($json, true, $wechat->isEncrypt());
                //     } else {
                //         return $result;
                //     }
                // }
            } catch (\Exception $e) {
                trace("微信{$appid}接口调用异常，{$e->getMessage()}",'wxopen');
            }
            return 'success';
        }
    }
}
